﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace EvoBoost.Core
{
	static class MathUtils
	{
		private static readonly Random random = new Random();

		public const double Eps = 0.000001;
		
		public static int SampleFromDiscreteDistribution(IList<double> weights)
		{
			// Check distribution
			Debug.Assert(Math.Abs(weights.Sum() - 1.0) < Eps);
			
			// Sample from distribution
			double uniformRandom = random.NextDouble();
			double sum = 0;
			int index = 0;
			do{
				sum += weights[index++];
			} while (sum < uniformRandom);

			// Check result
			int result = index - 1;
			Debug.Assert(result >= 0 && result < weights.Count);

            return result;
		}
	}
}
